package com.crape.topic.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.crape.account.bo.IAccountBO;
import com.crape.account.bo.IUploadBO;
import com.crape.common.bean.LoginUser;
import com.crape.common.constants.ConstantCode;
import com.crape.common.constants.MessageCode;
import com.crape.common.enums.ArticleStatusType;
import com.crape.common.enums.SubjectStatusType;
import com.crape.common.exceptions.BOException;
import com.crape.common.model.AccountInfo;
import com.crape.common.model.Article;
import com.crape.common.model.ArticleComment;
import com.crape.common.model.ArticleReply;
import com.crape.common.model.ImageInfo;
import com.crape.common.model.Subject;
import com.crape.common.thread.ThreadObjManager;
import com.crape.common.utils.PageUtils;
import com.crape.topic.bo.IArticleBO;
import com.crape.topic.bo.ISubjectBO;
import common.Logger;

@Controller
public class ArticleController {
	
	static Logger logger = Logger.getLogger(ArticleController.class);
	
	private ISubjectBO subjectBOImpl;
	private IArticleBO articleBOImpl;
	private IAccountBO accountBOImpl;
	private IUploadBO  uploadBOImpl;

	@Autowired
	public void setsubjectBOImpl(ISubjectBO subjectBOImpl) {
		this.subjectBOImpl = subjectBOImpl;
	}

	@Autowired
	public void setarticleBOImpl(IArticleBO articleBOImpl) {
		this.articleBOImpl = articleBOImpl;
	}

	@Autowired
	public void setAccountBOImpl(IAccountBO accountBOImpl) {
		this.accountBOImpl = accountBOImpl;
	}
	
	@Autowired
	public void setUploadBOImpl(IUploadBO uploadBOImpl) {
		this.uploadBOImpl = uploadBOImpl;
	}
    
	@RequestMapping("/topic/articles.jsp")
	public String articles(ModelMap modelMap, Integer pageNo) {
		if (pageNo == null || pageNo == 0) {
			pageNo = 1;
		}
		Integer pageSize = 20;
		Integer startIndex = PageUtils.getStartIndex(pageNo, pageSize);
		List<Article> articles = articleBOImpl.getAllArticles(startIndex, pageSize);
		modelMap.put("articles", articles);
		modelMap.put("pageNo", pageNo);
		modelMap.put("pageNumArray", PageUtils.getPagedNumArray(articleBOImpl.countAllArticles(), pageSize));
		// 热门文章
		List<Article> hotArticles = articleBOImpl.getHotArticles();
		modelMap.put("hotArticles", hotArticles);
		return "/topic/articles.html";
	}

	@RequestMapping("/topic/article.jsp")
	public String article(ModelMap modelMap, Long id, Integer pageNo) {
		if (id == null) {
			modelMap.put("message", "错误的访问链接");
			return "/alert.html";
		}
		if (pageNo == null || pageNo == 0) {
			pageNo = 1;
		}
		Integer pageSize = 20;
		Integer startIndex = PageUtils.getStartIndex(pageNo, pageSize);
		Article article = articleBOImpl.getArticleDetailId(id);
		if (article == null) {
			modelMap.put("message", "文章不存在");
			return "/alert.html";
		}
		Long visitorid = ThreadObjManager.getLoginUser().getAccountid();
		articleBOImpl.addVisitor(visitorid, id);
		AccountInfo accountInfo = accountBOImpl.getAccountInfoById(article.getAccountid());
		article.setCreator(accountInfo);
		article.setUsername(accountInfo.getUsername());
		modelMap.put("article", article);
		modelMap.put("accountInfo", accountInfo);
		List<ArticleComment> articleComments = articleBOImpl.getArticleCommentByArticleId(id, startIndex, pageSize);
		modelMap.put("articleComments", articleComments);
		List<Article> authorArticles = articleBOImpl.getAuthorOtherArticles(article.getAccountid(), id);
		modelMap.put("authorArticles", authorArticles);
		Subject subject = subjectBOImpl.getSubjectById(article.getSubjectid());
		modelMap.put("subject", subject);
		List<Article> subjectArticles = articleBOImpl.getSubjectOtherArticles(article.getSubjectid(), id);
		modelMap.put("subjectArticles", subjectArticles);
		modelMap.put("pageNo", pageNo);
		modelMap.put("pageNumArray", PageUtils.getPagedNumArray(article.getComments(), pageSize));
		return "/topic/article.html";
	}

	@RequestMapping("/topic/addComment.jsp")
	public String addComment(ModelMap modelMap, ArticleComment articleComment) {
		if (articleComment == null || articleComment.getArticleid() == null) {
			modelMap.put("message", "参数错误！");
			return "/alert.html";
		}
		if (articleComment.getComment() == null || articleComment.getComment().isEmpty()) {
			modelMap.put("message", "评论不能为空！");
			return "/alert.html";
		}
		Long accountid = ThreadObjManager.getLoginUser().getAccountid();
		articleComment.setAccountid(accountid);
		articleBOImpl.addComment(articleComment);
		String redirect = "redirect:/topic/article.jsp?id=" + articleComment.getArticleid();
		return redirect;
	}

	@RequestMapping("/topic/addReply.jsp")
	public String addReply(ModelMap modelMap, ArticleReply articleReply) {
		if (articleReply == null || articleReply.getArticleid() == null
				||articleReply.getCommentid() == null
				||articleReply.getReaccountid() == null) {
			modelMap.put("message", "参数错误！");
			return "/alert.html";
		}
		if (articleReply.getReply() == null || articleReply.getReply().isEmpty()) {
			modelMap.put("message", "回复不能为空！");
			return "/alert.html";
		}
		Long accountid = ThreadObjManager.getLoginUser().getAccountid();
		articleReply.setAccountid(accountid);
		articleBOImpl.addReply(articleReply);
		String redirect = "redirect:/topic/article.jsp?id=" + articleReply.getArticleid();
		return redirect;
	}
	
	@RequestMapping(value="/topic/uploadArticleImages.jsp" ,method=RequestMethod.POST)
	public String uploadImages(HttpServletRequest request, @RequestParam("fileUpload")MultipartFile fileUpload, ModelMap modelMap, Article article) {
		this.initArticleParams(modelMap);
		try {
			ImageInfo imageInfo = uploadBOImpl.uploadImage(request, fileUpload, ConstantCode.imageArticleSize);
			article.setImagename(imageInfo.getName());
			modelMap.put("imageInfo", imageInfo);
            return "/topic/addArticle.html";
		} catch (BOException e) {
			e.printStackTrace();
			logger.error("uploadImages Error", e);
			modelMap.put("message", e.getMessage());
            return "/topic/addArticle.html";
		}
    }

	@RequestMapping("/topic/addArticleInit.jsp")
	public String addArticleInit(ModelMap modelMap) {
		this.initArticleParams(modelMap);
		return "/topic/addArticle.html";
	}

	@RequestMapping("/topic/addArticle.jsp")
	public String addArticle(ModelMap modelMap, Article article) {
		if (!this.validate(modelMap, article)) {
			return this.addArticleInit(modelMap);
		}
		LoginUser loginUser = ThreadObjManager.getLoginUser();
		article.setAccountid(loginUser.getAccountid());
		article.setTitle(article.getTitle().trim());
		article.setLabel(article.getLabel().trim());
		articleBOImpl.addArticle(article);
		return "addArticleSuccess.html";
	}
	
	@RequestMapping(value="/topic/updateUploadArticleImages.jsp" ,method=RequestMethod.POST)
	public String updateUploadImages(HttpServletRequest request, @RequestParam("fileUpload")MultipartFile fileUpload, ModelMap modelMap, Article article) {
		try {
			ImageInfo imageInfo = uploadBOImpl.uploadImage(request, fileUpload, ConstantCode.imageArticleSize);
			article.setImagename(imageInfo.getName());
			modelMap.put("imageInfo", imageInfo);
		} catch (BOException e) {
			e.printStackTrace();
			logger.error("uploadImages Error", e);
			modelMap.put("message", e.getMessage());
		}
		this.initArticleParams(modelMap);
		modelMap.put("article", article);
		return "/topic/updateArticle.html";
    }

	@RequestMapping("/topic/updateArticleInit.jsp")
	public String updateArticleInit(ModelMap modelMap, Long id) {
		this.initArticleParams(modelMap);
		Article article = articleBOImpl.getArticleId(id);
		modelMap.put("article", article);
		return "/topic/updateArticle.html";
	}

	@RequestMapping("/topic/updateArticle.jsp")
	public String updateArticle(ModelMap modelMap, Article article) {
		if (!this.validate(modelMap, article)) {
			return this.updateArticleInit(modelMap, article.getId());
		}
		LoginUser loginUser = ThreadObjManager.getLoginUser();
		article.setAccountid(loginUser.getAccountid());
		article.setTitle(article.getTitle().trim());
		article.setLabel(article.getLabel().trim());
		articleBOImpl.updateArticle(article);
		return "/topic/updateArticleSuccess.html";
	}

	private void initArticleParams(ModelMap modelMap) {
		Subject subject = new Subject();
		subject.setStatus(SubjectStatusType.published.getCode());
		List<Subject> subjectList = subjectBOImpl.listSubjects(subject);
		modelMap.put("subjectList", subjectList);
		Article article = new Article();
		LoginUser loginUser = ThreadObjManager.getLoginUser();
		article.setAccountid(loginUser.getAccountid());
		article.setStatus(ArticleStatusType.draft.getCode());
		List<Article> draftList = articleBOImpl.getArticles(article);
		modelMap.put("draftList", draftList);
	}

	private boolean validate(ModelMap modelMap, Article article) {
		if (article == null) {
			modelMap.put(MessageCode.key, MessageCode.PARAMS_IS_NULL);
			return false;
		}
		modelMap.put("article", article);
		if (article.getTitle() == null || article.getTitle().isEmpty()) {
			modelMap.put(MessageCode.key, MessageCode.TOPIC_ARTICLE_TITLE_NULL);
			return false;
		}
		if (article.getContent() == null || article.getContent().isEmpty()) {
			modelMap.put(MessageCode.key, MessageCode.TOPIC_ARTICLE_CONTENT_NULL);
			return false;
		}
		if (article.getSubjectid() == null) {
			modelMap.put(MessageCode.key, MessageCode.TOPIC_ARTICLE_SUBJECT_NULL);
			return false;
		}
		return true;
	}
	
	@RequestMapping("/topic/updateArticleStatus.json")
    public ModelAndView updateArticleStatus(Long articleid, Integer status) {
		ModelAndView mv = new ModelAndView();
		if(articleid==null||status==null){
			mv.addObject("flag", 1);
			mv.addObject("message", "参数错误！");
			return mv;
		}
    	Article article = articleBOImpl.getArticleId(articleid);
    	Long accountid = null;
    	if(article!=null){
    		accountid = article.getAccountid();
    		articleBOImpl.updateArticleStatus(accountid, articleid, status);
    	}
    	String text = "";
    	if(status.equals(ArticleStatusType.draft.getCode())){
    		text = "取消发布";
    	}else if(status.equals(ArticleStatusType.published.getCode())){
    		text = "发布";
    	}else if(status.equals(ArticleStatusType.discard.getCode())){
    		text = "删除";
    	}else {
    		mv.addObject("flag", 1);
			mv.addObject("message", "参数错误！");
			return mv;
    	}
    	mv.addObject("flag", 0);
		mv.addObject("message", text+"成功！");
        return mv;
    }

}
